/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package MainClasses;
import MainClasses.Event.*;

import java.net.*;
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
import javax.mail.*;
import javax.mail.internet.*;
import com.jscape.inet.smtpssl.*;
import com.jscape.inet.email.*;

/**
 *
 * @author andrewcutler
 */
public class WebHandler {

    private Preferences prefs;
    private boolean connectionFailed;
    
    public WebHandler(Preferences prefs, int num)
    {
        this.prefs = prefs;
        BufferedReader in;
        PrintWriter out;
        try
        {
            MyDate today = main.getCurrentDate();
            String urlString = "http://homework.harker.org/view/student.php?t=xml&i=" + prefs.getID() + "&s=104&mode=weekly&d="+(today.getDayOfMonth() + 7*num)+"&m="+today.getMonth()+"&y="+today.getYear();
            System.out.println(urlString);
            URL xmlpage = new URL(urlString);
            in = new BufferedReader(new InputStreamReader(xmlpage.openStream()));
            String inputLine = "";
            File file = new File(prefs.getFileName(num));
            out = new PrintWriter(new FileWriter(file));
            while((inputLine = in.readLine()) != null)
            {
                out.println(inputLine);
            }
            in.close();
            out.close();
            connectionFailed = false;
        }
            
        
        catch(Exception e)
        {
            connectionFailed = true;
            System.out.println("ERROR: " + e);
        }
    }

        
        public boolean connectionFailed()
        {
            return connectionFailed;
        }
        
    public static String SMTP_HOST = "smtp.sbcglobal.net";
    public static String MESSAGE_TITLE = "Assignments for Student #";
    
    
    public void emailAssignments()
    {
        String email;
        if(prefs.getEmail().equals(""))
        {
            email = JOptionPane.showInputDialog("Enter email:");
            prefs.setEmail(email);
        }
        email = prefs.getEmail();
        
        
        try{
        String from = "homeworkmanager@gmail.com";
        String smtpHost = WebHandler.SMTP_HOST;
        String to = email;
        String messageTitle = WebHandler.MESSAGE_TITLE + prefs.getID();
        String messageBody = createMessageBody();
        
        

        // Get system properties
        Properties props = System.getProperties();

        // Setup mail server
        props.put("mail.smtp.host", smtpHost);

        // Get session
        Session session = 
            Session.getDefaultInstance(props, null);

        // Define message
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from, "Homework Manager"));
        message.addRecipient(Message.RecipientType.TO, 
          new InternetAddress(to));
        message.setSubject(messageTitle);
        message.setText(messageBody);

        // Send message
        Transport.send(message);
        }
        catch(Exception e)
        {
            new SmtpGmail().emailGmail(new String[]{email, WebHandler.MESSAGE_TITLE + prefs.getID(), createMessageBody()});
            System.out.println(e);
        }
        
        
    }
    
    
    private String createMessageBody()
    {
        String returnString = "Assignments for Student #" + prefs.getID() + " \n ";
        ArrayList<Course> courses = prefs.getCourseManager().getCourses();
        for(Course c : courses)
        {
            returnString += "\n";
            returnString += c.getPeriodName() + ": " + c.getCourseName() + " - " + c.getTeacher();
            for(Event a : c.getEvents())
            {
                returnString += "\n \t";
                returnString += "• " + a.getName() + " :: " + a.getDescription();
            }
        }
        
        return returnString;
        
    }
    

 
private class SmtpGmail {
   
   public void emailGmail(String[] args) {
     SmtpSsl smtp = null;
     
     // gmail username - CHANGE THIS
     String username = "homeworkmanager@gmail.com";
     
     // gmail password - CHANGE THIS
     String password = "amandaismygirlfriend";
     
     // address to send mail to - CHANGE THIS
     String to = args[0];
     try {      
       // create a new SmtpSsl instance connecting securely via port 465 using implicit SSL
       smtp = new SmtpSsl("smtp.gmail.com",465);
       
       // establish secure connection
       smtp.connect();
       
       // login using gmail account details
       smtp.login(username,password);
       
       // create new email message
       EmailMessage message = new EmailMessage();
       message.setTo(to);
       message.setFrom(username);
       message.setSubject(args[1]);
       message.setBody(args[2]);
       
       // send message
       smtp.send(message);
       
       // disconnect      
       smtp.disconnect();      
     } catch(Exception e) {
       // capture any exception and print to console
       e.printStackTrace();
     } 
   }
 }
}
